package com.ougy.reshop.interceptor;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.ougy.reshop.model.Region;
import com.ougy.reshop.service.ISRegion;


public class CheckPlaceFilter implements Filter{
	protected FilterConfig filterConfig = null;
	private Logger logger = Logger.getLogger(getClass());
	private static final String cookieKey = "reshop_city_id";
	private ISRegion sRegion;
	
	@Override
	public void destroy() {
		filterConfig=null;
	}

	@Override
	public void doFilter(ServletRequest servletRequest,
			ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		Cookie cookies[] = request.getCookies();
		Cookie sCookie = null;
		String sValue = null;
		String sName = null;
		for (int i = 0; i < cookies.length; i++) {
			sCookie = cookies[i];
			sName = sCookie.getName();
			if (sName.equals(cookieKey)) {
				sValue = sCookie.getValue();
				Region city=sRegion.load(Integer.parseInt(sValue));
				logger.debug("ȡ�� 取到当前城市id:" + city.getId());
				logger.debug("取得当前城市名:"+city.getName());
				request.setAttribute("city",city);
				filterChain.doFilter(servletRequest, servletResponse);
				return;
			}
		}
		logger.debug("没有取得当前城市");
		addDefaultPlaceCookie(response);
		filterChain.doFilter(servletRequest, servletResponse);
	}
	
	private void addDefaultPlaceCookie(HttpServletResponse response) {
		Cookie cookie = new Cookie(cookieKey, "197");
		cookie.setMaxAge(60 * 60 * 24 * 30 * 12);
		response.addCookie(cookie);
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig=filterConfig;
		WebApplicationContext  wac = WebApplicationContextUtils.getRequiredWebApplicationContext(filterConfig.getServletContext());
		sRegion=(ISRegion) wac.getBean("SRegion");
	}


}
